package com.acme.test;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.hamcrest.core.Is;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.acme.StartServer;
import com.acme.domain.Operationtype;
import com.acme.domain.Order;
import com.acme.domain.Orderstatus;
import com.acme.domain.Responses;
import com.acme.domain.StartClient;
import com.acme.domain.Writer;
import com.acme.domain.request.PlaceOrderRequest;
import com.acme.domain.response.OrderChangeInfo;

public class MatchTestCase {

	@BeforeClass
	public static void setUpBeforeClass(){
		StartServer.start(2013);
	}
	
	@Before 
	public void setUp() throws Exception {
		StartClient.start("127.0.0.1", 2013, "Oleg");
	}

	@Test
	public void shouldRecieveFilledWhenMatchOrders() throws InterruptedException{
		List<Order> orderList = new ArrayList<Order>(); 
		orderList.add( new Order("Oleg", Operationtype.BUY, "IBM", 10, 15f, 1) );
		orderList.add( new Order("Oleg", Operationtype.SELL, "IBM", 5, 13f, 2) );
		
		for (Order order : orderList) {
			Writer.writeRequest(new PlaceOrderRequest(order));
		}
		synchronized (Responses.get()) {
			if (Responses.get().size()<2)
				Responses.get().wait();
			checkFilledOrder(Responses.get().get(1), orderList.get(1));
		}
	}
	
	private void checkFilledOrder(OrderChangeInfo resp, Order order){
		assertTrue(resp.getOrder().equals(order));
		assertThat(resp.getOrder().getStatus(), Is.is(Orderstatus.EXECUTED));
	}
	
	@After
	public void tearDown() throws Exception{
		Responses.get().clear();
		StartClient.shutdown();
	}
	
	@AfterClass
	public static void tearDownAfterClass() throws Exception{
		StartServer.shutdown();
	}
}
